//
//  SEATools.m
//  GoodsHoster
//
//  Created by 梧桐树 on 16/4/6.
//  Copyright © 2016年 梧桐树. All rights reserved.
//

#import "SEATools.h"

@implementation SEATools

#pragma mark 正则匹配手机号

+ (BOOL)checkTelNumber:(NSString *) telNumber
{
    //移动号段：
    //    134 135 136 137 138 139 147 150 151 152 157 158 159 178 182 183 184 187 188
    //    联通号段：
    //    130 131 132 145 155 156 175 176 185 186
    //    电信号段：
    //    133 149 153 177 180 181 189
    //    虚拟运营商:
    //    170
    NSString *pattern =@"^1(3[0-9]|5[0-35-9]|8[025-9]|4[579]|7[05-8])\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
    
}
#pragma mark 正则匹配用户密码6-18位数字和字母组合
+ (BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

#pragma mark 正则匹配用户姓名,20位的中文或英文
+ (BOOL)checkUserName : (NSString *) userName
{
    NSString *pattern = @"^[a-zA-Z一-龥]{1,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:userName];
    return isMatch;
    
}


#pragma mark 正则匹配用户身份证号15或18位
+ (BOOL)checkUserIdCard: (NSString *) idCard
{
    NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:idCard];
    return isMatch;
    
}

#pragma mark 正则匹员工号,12位的数字
+ (BOOL)checkEmployeeNumber : (NSString *) number
{
    NSString *pattern = @"^[0-9]{12}";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:number];
    return isMatch;
    
}

#pragma  mark 正则匹配URL
+ (BOOL)checkURL : (NSString *) url
{
    NSString *pattern = @"^[0-9A-Za-z]{1,50}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:url];
    return isMatch;
    
}

#pragma mark 16位色值转颜色
//使用方法，传入字符串格式@"#XXXXXX"
+(UIColor *)stringToColor: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 charactersif ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appearsif ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

#pragma mark 网络请求
//拼接图片地址（url）
+(NSURL *)getImaurl:(NSString *)img{
    
    return [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGEWEB,img]];
}
#pragma mark 小菊花转起来
//获取当前界面
+(UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}
//创建小菊花
+(UIActivityIndicatorView*)getJuhua{
    UIActivityIndicatorView *testActivityIndicator=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    testActivityIndicator.center = CGPointMake(WIDTH/2, HEIGHT/2);//只能设置中心，不能设置大小
    
    testActivityIndicator.color = [self stringToColor:@"30A837"]; // 改变圈圈的颜色； iOS5引入
    [testActivityIndicator setHidesWhenStopped:YES]; //当旋转结束时隐藏
    [testActivityIndicator setHidden:NO];
    [testActivityIndicator startAnimating]; // 开始旋转
    return testActivityIndicator;
    
}
//创建全屏View
+(UIView *)getMyView{
    
    UIView *hi=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    hi.userInteractionEnabled=NO;
    return hi;
}

#pragma mark 钥匙链
//辅助方法
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge id)kSecClassGenericPassword,(__bridge id)kSecClass,
            service, (__bridge id)kSecAttrService,
            service, (__bridge id)kSecAttrAccount,
            (__bridge id)kSecAttrAccessibleAfterFirstUnlock,(__bridge id)kSecAttrAccessible,
            nil];
}
//保存钥匙链的dic
+ (void)save:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}
//根据Key获取已有钥匙链
+ (id)load:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}
//删除钥匙链
+ (void)dele:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
}
#pragma mark 加密解密算法
+(NSString *)screct:(NSString *)data{
    
    //UTF8转码
    NSString *dataUTF8 = [data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    NSMutableString *mudata=[NSMutableString stringWithString:dataUTF8];
    
    //NSLog(@"%@",mudata);
    //NSLog(@"%d",mudata.length);
    
    //ASCLL转码
    
    NSRange range=NSMakeRange(0, 1);
    int a=mudata.length;
    NSMutableArray *arry=[[NSMutableArray alloc]init];
    for (int i=0; i<a; i++) {
        NSString * to = [mudata substringToIndex:1];
        //
        [arry addObject:to];
        [mudata deleteCharactersInRange:range];
    }
    NSMutableArray *arry2=[[NSMutableArray alloc]init];
    // NSLog(@"%@",arry);
    for (int i=0; i<arry.count; i++) {
        int asciiCode = [[arry objectAtIndex:i] characterAtIndex:0];
        NSString *askstr=[NSString stringWithFormat:@"%d",asciiCode];
        askstr=[NSString stringWithFormat:@"%ld%@",askstr.length,askstr];
        [arry2 addObject:askstr];
    }
    // NSLog(@"%@",arry2);
    NSMutableString *sec=[[NSMutableString alloc]init];
    for (int i=0; i<arry2.count; i++) {
        [sec appendString:[arry2 objectAtIndex:i]];
    }
    // NSLog(@"111%@",sec);
    //时间戳加密
    NSDate * senddate=[NSDate date];
    
    NSDateFormatter * dateformatter=[[NSDateFormatter alloc] init];
    //yyMMyyHHddmmssdms
    [dateformatter setDateFormat:@"yyMMyyHHddmm2"];
    
    NSString * locationString=[dateformatter stringFromDate:senddate];
    // NSLog(@"%@",locationString);
    
    [sec insertString:locationString atIndex:0];
    // NSLog(@"%@",sec);
    return sec;
}
+(NSString *)discrect:(NSString *)data{
    //去除时间戳
    NSMutableString *sec=[NSMutableString stringWithString:data];
    NSRange range=NSMakeRange(0, 13);
    [sec deleteCharactersInRange:range];
    //ASCLL逆向
    //NSLog(@"AAA%@",sec);
    int num;
    
    NSRange range2;
    NSRange range3=NSMakeRange(0, 1);
    
    NSMutableArray *arry=[[NSMutableArray alloc]init];
    do{
        num=[[sec substringToIndex:1] intValue];
        range2=NSMakeRange(0, num);
        [sec deleteCharactersInRange:range3];
        
        [arry addObject:[sec substringToIndex:num]];
        [sec deleteCharactersInRange:range2];
        
        
    }while (sec.length>0);
    
    NSMutableArray *arry2=[[NSMutableArray alloc]init];
    for (int i=0; i<arry.count; i++) {
        NSString *aa=[arry objectAtIndex:i];
        char asciiCode = [aa intValue];
        NSString *askstr=[NSString stringWithFormat:@"%c",asciiCode];
        [arry2 addObject:askstr];
    }
    
    //逆向
    NSMutableString *utf8str=[[NSMutableString alloc]init];
    
    for (int i=0; i<arry2.count; i++) {
        [utf8str appendString:[arry2 objectAtIndex:i]];
    }
    //NSLog(@"%@",utf8str);
    //UTF8逆转
    NSString* datau8=[utf8str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //unicode逆转
    //NSString *datau8=[self replaceUnicode:utf8str];
    return datau8;
}

#pragma mark 获取次日或之后时间
//传入值date为[nsdate date]
+(NSString *)getTomorrowDay:(NSDate *)aDate dayjia:(int)dayjia
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:aDate];
    //这个是当前日期向后推得日期，如果向后推一天，dayjia=1
    [components setDay:([components day]+dayjia)];
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc]init];
    //如果想获得年，就在前面拼接YYYY
    [dateday setDateFormat:@"YYYY-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}

@end
